package com.xb.system.controller;


import cn.hutool.core.io.FileUtil;
import com.xb.common.result.Result;
import com.xb.system.service.SysDocService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjl
 * @since 2024-05-08
 */
@Api(tags = "模板下载") //Swagger生成api的提示
@RestController
@RequestMapping("/admin/system/sysDoc")
public class SysDocController {

    @Value("${files.upload.path}")
    private String path;//磁盘文件路径

    @Resource
    private SysDocService sysDocService;

    //文件上传
//    @ApiOperation(value = "文件上传")
//    @PostMapping("/upload")
//    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
//        String url = sysDocService.uploadDoc(file,path);
//        return Result.ok(url);
//    }
//
//    //文件下载
    @ApiOperation(value = "模板下载",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        String TEMPLATE_FILE_NAME = "模板.xlsx";
        try {
            // 获取模板文件的路径
            ClassPathResource resource = new ClassPathResource(TEMPLATE_FILE_NAME);

            // 设置输出流的格式
//            response.addHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(TEMPLATE_FILE_NAME, "UTF-8"));
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(TEMPLATE_FILE_NAME, "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);

            // 读取文件的字节流
            byte[] bytes = Files.readAllBytes(resource.getFile().toPath());
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            // 处理文件不存在或无法读取的情况
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error downloading the file: " + e.getMessage());
        }
    }
}

